import React from "react";

class App extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      number: 0,
    };
  }

  handleChange = () => {
    this.setState(() => {
      return {
        // 返回 0,1,2 这三个随机数
        number: Math.floor(Math.random() * 3),
      };
    });
  };

  render() {
    console.log("父组件渲染了", this.state.number);
    return (
      <div>
        <button onClick={this.handleChange}>重新生成</button>
        <AppChild number={this.state.number} />
      </div>
    );
  }

  shouldComponentUpdate(nextProps, nextState) {
    console.log(
      "当前组件state",
      this.state.number,
      "状态变化后的state",
      nextState.number
    );
    // if(this.state.number !== nextState.number){
    //   return true
    // }
    // return false;
    return this.state.number !== nextState.number;
  }
}

class AppChild extends React.Component {
  constructor(props) {
    super(props);
  }

  render() {
    console.log("子组件渲染了", this.props.number);
    return (
      <div>
        <h1>{this.props.number}</h1>
      </div>
    );
  }

  shouldComponentUpdate(nextProps, nextState) {
    console.log(
      "当前组件props",
      this.props.number,
      "状态变化后的props",
      nextProps.number
    );

    return this.props.number !== nextProps.number;
  }
}

export default App;
